package src

import (
	"encoding/json"
	"fmt"
	"io"
	"os"

	. "github.com/soekchl/myUtils"
)

func readFile(fileName string) []byte {
	fi, err := os.Open(fileName)
	if err != nil {
		Error(fileName, err)
		return nil
	}
	defer fi.Close()
	buff, _ := io.ReadAll(fi)
	return buff
}

func outFile(fileName, outFileStr string) {
	fi, err := os.Create(fileName)
	if err != nil {
		Error(err)
		return
	}
	lastProcFileName = fileName // NOTE 记录最后保存文件
	fi.WriteString(outFileStr)
	fi.Close()
}

func outPutJson(info interface{}, filename string) {
	buff, err := json.MarshalIndent(&info, "", "  ")
	if err != nil {
		Error(err)
		return
	}
	outFile(filename, string(buff))
}

func saveJson(info interface{}, filename string, isBack bool) {
	buff, err := json.MarshalIndent(&info, "", "  ")
	if err != nil {
		Error(err)
		return
	}
	if isBack {
		os.Rename(filename, fmt.Sprintf("%s_back", filename))
	} else {
		os.Remove(filename)
	}
	outFile(filename, string(buff))
}
